package com.ruoyi.distributor.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alipay.api.domain.WalletInfo;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.distributionConfig.domain.DistributionConfig;
import com.ruoyi.distributionConfig.service.IDistributionConfigService;
import com.ruoyi.distributionGrade.domain.DistributionGrade;
import com.ruoyi.distributionGrade.service.IDistributionGradeService;
import com.ruoyi.distributionLog.domain.DistributionLog;
import com.ruoyi.distributionLog.service.IDistributionLogService;
import com.ruoyi.distributor.domain.CommissionInfoVo;
import com.ruoyi.distributor.domain.DistributorDetailVo;
import com.ruoyi.distributor.domain.DistributorInfoVo;
import com.ruoyi.relation.domain.DistributionRelation;
import com.ruoyi.relation.mapper.DistributionRelationMapper;
import com.ruoyi.relation.service.IDistributionRelationService;
import com.ruoyi.relationOrder.domain.DistributionOrderRelation;
import com.ruoyi.relationOrder.mapper.DistributionOrderRelationMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.wallet.domain.DistributionWallet;
import com.ruoyi.wallet.service.IDistributionWalletService;
import com.ruoyi.withdraw.service.IDistributionWithdrawService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.distributor.mapper.DistributionUserMapper;
import com.ruoyi.distributor.domain.DistributionUser;
import com.ruoyi.distributor.service.IDistributionUserService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

/**
 * 分销用户信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-11
 */
@Service
public class DistributionUserServiceImpl implements IDistributionUserService 
{
    private static final Logger log = LoggerFactory.getLogger(DistributionUserServiceImpl.class);

    @Autowired
    private DistributionUserMapper distributionUserMapper;

    @Autowired
    private DistributionRelationMapper distributionRelationMapper;

    @Autowired
    private DistributionOrderRelationMapper distributionOrderRelationMapper;

    @Autowired
    private IDistributionWalletService walletService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IDistributionGradeService distributionGradeService;

    @Autowired
    private IDistributionRelationService distributionRelationService;

    @Autowired
    private IDistributionConfigService distributionConfigService;

    @Autowired
    private IDistributionLogService distributionLogService;


    /**
     * 根据分销员编码查询分销用户信息
     *
     * @param distributorCode 分销员编码
     * @return 分销用户信息
     */
    @Override
    public DistributionUser selectDistributionUserByDistributorCode(String distributorCode) {
        return distributionUserMapper.selectDistributorByDistributorCode(distributorCode);
    }

    /**
     * 绑定邀请关系
     *
     * @param inviteCode 邀请码
     * @param newDistributorId 新分销员ID
     * @return 结果
     */
    @Override
    @Transactional
    public int bindInvitationRelation(String inviteCode, Long newDistributorId) {
        // 1. 通过邀请码查询邀请人信息
        DistributionUser inviter = distributionUserMapper.selectDistributorByDistributorCode(inviteCode);
        if (inviter == null) {
            throw new ServiceException("邀请码无效");
        }

        // 2. 校验邀请人状态
        if (!"0".equals(inviter.getStatus()) || !"0".equals(inviter.getDelFlag()) || !"1".equals(inviter.getAuthStatus())) {
            throw new ServiceException("邀请人状态异常，无法建立邀请关系");
        }

        // 3. 查询新分销员信息
        DistributionUser newDistributor = distributionUserMapper.selectDistributionUserByDistributorId(newDistributorId);
        if (newDistributor == null) {
            throw new ServiceException("新分销员信息不存在");
        }

        // 4. 检查是否试图绑定自己
        if (inviter.getDistributorId().equals(newDistributorId)) {
            throw new ServiceException("不能绑定自己为上级");
        }

        // 5. 检查是否已存在绑定关系
        DistributionRelation existRelation = distributionRelationService.selectRelationByDistributorIdAndSubordinateId(
                inviter.getDistributorId(), newDistributorId);
        if (existRelation != null) {
            throw new ServiceException("已存在绑定关系");
        }

        // 6. 检查新分销员是否已经有上级
        if (newDistributor.getFatherId() != null && newDistributor.getFatherId() > 0) {
            throw new ServiceException("该分销员已绑定上级，无法重复绑定");
        }

        // 7. 设置新分销员的上级ID
        newDistributor.setFatherId(inviter.getDistributorId());
        distributionUserMapper.updateDistributionUser(newDistributor);

        // 8. 如果新分销员已审核通过，立即更新团队关系
        if ("1".equals(newDistributor.getAuthStatus())) {
            updateSuperiorTeamRelation(newDistributor);
            createDistributionRelations(newDistributor);
        }

        // 9. 记录绑定日志
        recordDistributionLog(
                inviter.getDistributorId(),
                "1",
                "绑定一级下级",
                "绑定关系",
                "新绑定下级分销员ID：" + newDistributorId,
                inviteCode);

        return 1;
    }


    /**
     * 更新上级团队关系 - 审核通过时调用
     */
    public void updateSuperiorTeamRelationOnApproval(DistributionUser distributionUser) {
        if (distributionUser.getFatherId() != null && distributionUser.getFatherId() != 0L) {
            // 计算当前分销员的团队规模
            long teamCount = calculateSubordinateTeamCount(distributionUser.getDistributorId());

            // 更新直接上级的直接下级人数和团队人数
            DistributionUser father = distributionUserMapper.selectDistributionUserByDistributorId(distributionUser.getFatherId());
            if (father != null) {
                father.setDirectCount(father.getDirectCount() == null ? 1L : father.getDirectCount() + 1);
                father.setTeamCount(father.getTeamCount() == null ? teamCount : father.getTeamCount() + teamCount);
                distributionUserMapper.updateDistributionUser(father);

                // 如果有祖父级（一级分销员），更新祖父级的团队总人数
                if (father.getFatherId() != null && father.getFatherId() != 0L) {
                    DistributionUser grandfather = distributionUserMapper.selectDistributionUserByDistributorId(father.getFatherId());
                    if (grandfather != null) {
                        grandfather.setTeamCount(grandfather.getTeamCount() == null ? teamCount : grandfather.getTeamCount() + teamCount);
                        distributionUserMapper.updateDistributionUser(grandfather);
                    }
                }
            }
        }
    }

    /**
     * 获取分销用户详情
     *
     * @param userId 用户ID
     * @return 分销用户详情
     */
    @Override
    @Transactional
    public int autoBindRelation(String inviteCode, Long userId) {
        // 1. 验证分销功能是否开启
        DistributionConfig config = validateDistributionFunction();

        // 2. 验证邀请人信息
        DistributionUser inviter = validateInviter(inviteCode);

        // 3. 检查当前用户是否已经是分销员
        DistributionUser currentUser = distributionUserMapper.selectDistributionUserByUserId(userId);

        if (currentUser != null) {
            // 情况1：用户已经是分销员，处理分销员间的绑定关系
            return handleExistingDistributorBinding(inviter, currentUser);
        } else {
            // 情况2：用户不是分销员，只建立关注关系，不创建分销员身份
            return handleNonDistributorBinding(inviter, userId);
        }
    }

    /**
     * 处理非分销员绑定关系
     * 只建立关注关系，不创建分销员身份
     */
    private int handleNonDistributorBinding(DistributionUser inviter, Long userId) {
        // 检查是否已存在绑定关系
        DistributionRelation existingRelation = distributionRelationService.selectRelationByDistributorIdAndSubordinateId(
                inviter.getDistributorId(), userId);

        if (existingRelation != null) {
            // 如果已存在关系且有效，抛出异常
            if ("1".equals(existingRelation.getIsActive())) {
                throw new ServiceException("您已经关注过该分销员");
            } else {
                // 如果关系已失效，更新为有效状态
                existingRelation.setIsActive("1");
                existingRelation.setBindTime(new Date());
                existingRelation.setUpdateTime(new Date());
                distributionRelationService.updateDistributionRelation(existingRelation);
                return 1;
            }
        }

        // 区分普通用户与分销员的关系
        // 在查询时根据 subordinateId 对应的记录是否存在
        // DistributionUser 来判断是普通用户还是分销员

        // 创建新的关注关系记录
        DistributionRelation relation = new DistributionRelation();
        relation.setDistributorId(inviter.getDistributorId());
        relation.setSubordinateId(userId);
        relation.setRelationLevel("1"); // 默认为一级关系
        relation.setBindTime(new Date());
        relation.setIsActive("1"); // 有效
        relation.setStatus("0"); // 上架
        relation.setDelFlag("0"); // 未删除

        // 设置创建信息
        relation.setCreateBy(SecurityUtils.getUsername());
        relation.setCreateTime(new Date());

        // 插入关系记录
        distributionRelationService.insertDistributionRelation(relation);

        // 记录关注日志
        recordDistributionLog(
                inviter.getDistributorId(),
                "7",
                "用户关注",
                "用户扫码关注",
                "用户ID：" + userId + " 关注了分销员",
                inviter.getDistributorCode());

        return 1;
    }
// ... existing code ...




    /**
     * 查询分销用户信息
     *
     * @param distributorId 分销用户信息主键
     * @return 分销用户信息
     */
    @Override
    public DistributionUser selectDistributionUserByDistributorId(Long distributorId)
    {
        return distributionUserMapper.selectDistributionUserByDistributorId(distributorId);
    }

    /**
     * 根据用户ID查询分销用户信息
     *
     * @param userId 用户ID
     * @return 分销用户信息
     */
    @Override
    public DistributionUser selectDistributionUserByUserId(Long userId) {
        return distributionUserMapper.selectDistributionUserByUserId(userId);
    }

    /**
     * 检查用户是否已经申请成为分销员
     *
     * @param userId 用户ID
     * @return true:已经申请，false:没有申请
     */
    @Override
    public boolean checkUserHasDistributor(Long userId) {
        DistributionUser existing = distributionUserMapper.selectDistributionUserByUserId(userId);
        return existing != null;
    }

    /* ===========================================================  */

    /**
     * 审核分销员申请 - 新增方法
     */
    @Override
    @Transactional
    public int auditDistributor(Long distributorId, String authStatus, String remark) {
        // 1. 获取分销员信息
        DistributionUser distributor = distributionUserMapper.selectDistributionUserByDistributorId(distributorId);
        if (distributor == null) {
            throw new ServiceException("分销员信息不存在");
        }

        String oldAuthStatus = distributor.getAuthStatus();

        // 2. 更新审核状态
        distributor.setAuthStatus(authStatus);
        distributor.setRemark(remark);
        distributor.setUpdateTime(new Date());
        distributor.setUpdateBy(SecurityUtils.getUsername());

        // 3. 如果审核通过，处理团队关系
        if ("1".equals(authStatus) && !"1".equals(oldAuthStatus)) {
            // 设置绑定时间
            distributor.setBindTime(new Date());

            // 更新上级团队关系（只在审核通过时执行）
            updateSuperiorTeamRelation(distributor);

            // 建立分销关系记录
            createDistributionRelations(distributor);

            // 初始化钱包（如果还没有）
            initializeWalletIfNeeded(distributorId);
        }

        int result = distributionUserMapper.updateDistributionUser(distributor);

        // 4. 记录操作日志
        String action = "1".equals(authStatus) ? "审核通过" : "审核拒绝";
        recordDistributionLog(distributorId, "5", action, "平台审核分销员申请", remark, "");

        return result;
    }

    /**
     * 审核分销员申请 - 专门用于 updateDistributorApply 接口
     */
    @Override
    @Transactional
    public int auditDistributorApply(Long distributorId, String authStatus, String remark) {
        // 1. 获取分销员信息
        DistributionUser distributor = distributionUserMapper.selectDistributionUserByDistributorId(distributorId);
        if (distributor == null) {
            throw new ServiceException("分销员信息不存在");
        }

        String oldAuthStatus = distributor.getAuthStatus();

        // 2. 更新审核状态
        distributor.setAuthStatus(authStatus);
        distributor.setRemark(remark);
        distributor.setUpdateTime(new Date());
        distributor.setUpdateBy(SecurityUtils.getUsername());

        // 3. 如果审核通过，处理团队关系
        if ("1".equals(authStatus)) {
            // 审核通过，设置绑定时间
            distributor.setBindTime(new Date());

            // 如果是从待审核状态变为审核通过状态，则更新上级团队人数
            if ("0".equals(oldAuthStatus)) {
                updateSuperiorTeamRelationOnApproval(distributor);
                // 添加建立分销关系记录
                createDistributionRelations(distributor);
            }
        }

        int result = distributionUserMapper.updateDistributionUser(distributor);

        // 4. 记录操作日志
        String action = "1".equals(authStatus) ? "审核通过" : "审核拒绝";
        recordDistributionLog(distributorId, "5", action, "平台审核分销员申请", remark, "");

        return result;
    }

    /**
     * 分销员脱离上级关系
     */
    @Override
    @Transactional
    public int unbindSuperiorRelation(Long distributorId, String remark) {
        // 1. 获取分销员信息
        DistributionUser distributor = distributionUserMapper.selectDistributionUserByDistributorId(distributorId);
        if (distributor == null) {
            throw new ServiceException("分销员信息不存在");
        }

        // 2. 检查是否已经有上级
        if (distributor.getFatherId() == null || distributor.getFatherId() == 0L) {
            throw new ServiceException("该分销员没有上级，无需脱离");
        }

        Long oldFatherId = distributor.getFatherId();

        // 3. 解除上级关系
        distributor.setFatherId(0L);
        distributor.setUpdateTime(new Date());
        distributor.setUpdateBy(SecurityUtils.getUsername());

        int result = distributionUserMapper.updateDistributionUser(distributor);

        // 4. 更新上级团队人数（递减）
        updateSuperiorTeamRelationOnUnbind(oldFatherId, distributorId);

        // 5. 删除分销关系记录
        deleteDistributionRelations(distributorId);

        // 6. 记录操作日志
        recordDistributionLog(distributorId, "6", "脱离上级关系",
                "分销员脱离上级", "原上级ID：" + oldFatherId + "，脱离原因：" + remark, "");

        return result;
    }

    /**
     * 更新上级团队关系 - 脱离上级时调用（递减人数）
     */
    private void updateSuperiorTeamRelationOnUnbind(Long fatherId, Long subordinateId) {
        // 更新直接上级的直接下级人数和团队人数
        DistributionUser father = distributionUserMapper.selectDistributionUserByDistributorId(fatherId);
        if (father != null) {
            // 递减直接下级人数
            if (father.getDirectCount() != null && father.getDirectCount() > 0) {
                father.setDirectCount(father.getDirectCount() - 1);
            }

            // 递减团队总人数（需要计算该下级及其所有下级的团队人数）
            long teamCountToRemove = calculateSubordinateTeamCount(subordinateId);
            if (father.getTeamCount() != null && father.getTeamCount() >= teamCountToRemove) {
                father.setTeamCount(father.getTeamCount() - teamCountToRemove);
            }

            distributionUserMapper.updateDistributionUser(father);

            // 如果有祖父级，更新祖父级的团队总人数
            if (father.getFatherId() != null && father.getFatherId() != 0L) {
                DistributionUser grandfather = distributionUserMapper.selectDistributionUserByDistributorId(father.getFatherId());
                if (grandfather != null && grandfather.getTeamCount() != null && grandfather.getTeamCount() >= teamCountToRemove) {
                    grandfather.setTeamCount(grandfather.getTeamCount() - teamCountToRemove);
                    distributionUserMapper.updateDistributionUser(grandfather);
                }
            }
        }
    }

    /**
     * 计算下级分销员及其所有下级的团队总人数
     */
    private long calculateSubordinateTeamCount(Long distributorId) {
        DistributionUser distributor = distributionUserMapper.selectDistributionUserByDistributorId(distributorId);
        if (distributor == null) {
            return 0;
        }
        return distributor.getTeamCount() != null ? distributor.getTeamCount() : 1L;
    }

    /**
     * 删除分销关系记录
     */
    private void deleteDistributionRelations(Long subordinateId) {
        // 删除所有与该分销员相关的分销关系记录
        distributionRelationService.deleteRelationBySubordinateId(subordinateId);
    }

    /**
     * 初始化钱包（如果还没有）
     */
    private void initializeWalletIfNeeded(Long distributorId) {
        try {
            DistributionWallet existingWallet = walletService.selectWalletByDistributorId(distributorId);
            if (existingWallet == null) {
                initializeDistributionWallet(distributorId);
            }
        } catch (Exception e) {
            log.error("检查钱包状态异常", e);
            // 不抛出异常，避免影响审核流程
        }
    }

    /* ===========================================================  */

    /**
     * web端用户申请成为分销员的接口 - 支持二级分销模式
     *
     * @param distributionUser 分销用户信息
     * @return 0:成功，1:失败
     */
    @Override
    public int applyDistributor(DistributionUser distributionUser) {
        // 1. 验证分销功能是否开启
        DistributionConfig config = validateDistributionFunction();

        // 2. 检查用户申请状态
        DistributionUser existingUser = checkUserApplicationStatus(distributionUser.getUserId());

        // 3. 验证上级关系（二级分销逻辑核心）
        validateSuperiorRelation(distributionUser, config);

        // 4. 处理申请逻辑
        if (existingUser != null && "2".equals(existingUser.getAuthStatus())) {
            return updateRejectedApplication(existingUser, distributionUser);
        } else {
            return createNewApplication(distributionUser, config);
        }
    }

    /**
     * 验证分销功能是否开启并返回配置
     */
    private DistributionConfig validateDistributionFunction() {
        DistributionConfig config = distributionConfigService.selectDistributionConfigByConfigId(1L);
        if (config == null || !"Y".equals(config.getDistributionOpen())) {
            throw new ServiceException("分销功能未开启");
        }
        return config;
    }

    /**
     * 验证邀请人信息
     */
    private DistributionUser validateInviter(String inviteCode) {
        DistributionUser inviter = distributionUserMapper.selectDistributorByDistributorCode(inviteCode);
        if (inviter == null) {
            throw new ServiceException("邀请码无效");
        }

        // 校验邀请人状态
        if (!"0".equals(inviter.getStatus()) || !"0".equals(inviter.getDelFlag()) || !"1".equals(inviter.getAuthStatus())) {
            throw new ServiceException("邀请人状态异常，无法建立邀请关系");
        }

        return inviter;
    }

    /**
     * 处理已有分销员绑定关系
     */
    private int handleExistingDistributorBinding(DistributionUser inviter, DistributionUser currentUser) {
        // 检查分销员状态
        if (currentUser.getFatherId() != null && currentUser.getFatherId() > 0) {
            throw new ServiceException("您已绑定上级，无法重复绑定");
        }

        if (!"0".equals(currentUser.getStatus()) || !"1".equals(currentUser.getAuthStatus())) {
            throw new ServiceException("分销员状态异常，无法绑定关系");
        }

        // 校验不能绑定自己
        if (inviter.getDistributorCode().equals(currentUser.getDistributorCode())) {
            throw new ServiceException("不能绑定自己为上级");
        }

        // 检查分销层级规则
        validateDistributionLevel(inviter);

        // 使用统一的绑定逻辑
        return executeBinding(inviter, currentUser);
    }

    /**
     * 处理新建分销员绑定关系
     */
    private int handleNewDistributorBinding(DistributionUser inviter, Long userId, DistributionConfig config) {
        // 检查分销层级规则
        validateDistributionLevel(inviter);

        // 获取默认等级
        DistributionGrade defaultGrade = distributionGradeService.selectDefaultGrade();
        if (defaultGrade == null) {
            throw new ServiceException("未设置默认分销等级");
        }

        // 创建新的分销员记录
        DistributionUser newDistributor = createNewDistributor(userId, inviter.getDistributorId(), defaultGrade);

        // 插入分销员记录
        int result = distributionUserMapper.insertDistributionUser(newDistributor);
        if (result <= 0 || newDistributor.getDistributorId() == null) {
            throw new ServiceException("创建分销员记录失败");
        }

        // 初始化分销员钱包
        initializeDistributionWallet(newDistributor.getDistributorId());

        // 创建分销关系记录
        createDistributionRelationRecord(inviter.getDistributorId(), newDistributor.getDistributorId(), "1");

        // 更新团队关系（传入新分销员信息用于计算团队规模）
        updateTeamRelations(inviter, newDistributor, config);

        // 记录绑定日志
        recordDistributionLog(
                inviter.getDistributorId(),
                "1",
                "绑定一级下级",
                "自动绑定关系",
                "新绑定下级分销员ID：" + newDistributor.getDistributorId(),
                inviter.getDistributorCode());

        return 1;
    }

    /**
     * 创建新的分销员对象
     */
    private DistributionUser createNewDistributor(Long userId, Long fatherId, DistributionGrade defaultGrade) {
        DistributionUser newDistributor = new DistributionUser();
        newDistributor.setUserId(userId);
        newDistributor.setGradeId(defaultGrade.getGradeId());
        newDistributor.setFatherId(fatherId);
        newDistributor.setAuthStatus("1"); // 直接审核通过
        newDistributor.setStatus("0"); // 正常
        newDistributor.setDelFlag("0"); // 未删除
        newDistributor.setDistributorCode(IdUtils.generateDistributorCode());
        newDistributor.setTeamCount(1L); // 团队总人数初始化为1
        newDistributor.setDirectCount(0L); // 直接下级人数初始化为0
        newDistributor.setBindTime(new Date());

        // 获取用户信息设置基本信息
        SysUser sysUser = userService.selectUserById(userId);
        if (sysUser != null) {
            newDistributor.setRealName(sysUser.getNickName());
            newDistributor.setMobile(sysUser.getPhonenumber());
        }

        return newDistributor;
    }

    /**
     * 创建分销关系记录
     */
    private void createDistributionRelationRecord(Long distributorId, Long subordinateId, String relationLevel) {
        DistributionRelation relation = new DistributionRelation();
        relation.setDistributorId(distributorId);
        relation.setSubordinateId(subordinateId);
        relation.setRelationLevel(relationLevel);
        relation.setBindTime(new Date());
        relation.setIsActive("1");
        relation.setStatus("0");
        relation.setDelFlag("0");

        distributionRelationService.insertDistributionRelation(relation);
    }

    /**
     * 更新团队关系 - 修复团队人数计算逻辑
     */
    private void updateTeamRelations(DistributionUser inviter, DistributionUser newDistributor, DistributionConfig config) {
        // 计算新分销员的团队总人数（包括自己及其所有下级）
        long newTeamCount = calculateSubordinateTeamCount(newDistributor.getDistributorId());

        // 更新邀请人的直接下级人数（只加1，因为只增加了一个直接下级）
        inviter.setDirectCount(inviter.getDirectCount() == null ? 1L : inviter.getDirectCount() + 1);

        // 关键修复：更新邀请人的团队总人数（增加新分销员的整个团队人数）
        inviter.setTeamCount(inviter.getTeamCount() == null ? newTeamCount : inviter.getTeamCount() + newTeamCount);
        distributionUserMapper.updateDistributionUser(inviter);

        // 如果有二级关系，需要更新上级的团队人数
        if ("2".equals(config.getMaxLevel()) && inviter.getFatherId() != null && inviter.getFatherId() > 0) {
            DistributionUser father = distributionUserMapper.selectDistributionUserByDistributorId(inviter.getFatherId());
            if (father != null) {
                // 关键修复：祖父级增加整个新团队的规模
                father.setTeamCount(father.getTeamCount() == null ? newTeamCount : father.getTeamCount() + newTeamCount);
                distributionUserMapper.updateDistributionUser(father);
            }
        }
    }

    /**
     * 执行绑定操作 - 修复团队信息更新逻辑
     */
    private int executeBinding(DistributionUser inviter, DistributionUser newDistributor) {
        // 关键修复：在绑定前计算新分销员的团队规模
        long currentTeamCount = calculateSubordinateTeamCount(newDistributor.getDistributorId());

        // 设置新分销员的上级ID
        newDistributor.setFatherId(inviter.getDistributorId());
        distributionUserMapper.updateDistributionUser(newDistributor);

        // 如果新分销员已审核通过，立即更新团队关系
        if ("1".equals(newDistributor.getAuthStatus())) {
            // 关键修复：更新上级团队关系，传入正确的团队规模
            updateSuperiorTeamRelationWithTeamCount(newDistributor, currentTeamCount);
            createDistributionRelations(newDistributor);
        }

        // 记录绑定日志
        recordDistributionLog(
                inviter.getDistributorId(),
                "1",
                "绑定一级下级",
                "绑定关系",
                "新绑定下级分销员ID：" + newDistributor.getDistributorId() + "，团队规模：" + currentTeamCount,
                inviter.getDistributorCode());

        return 1;
    }

    /**
     * 验证分销层级规则
     * 检查邀请人是否已达到最大分销层级限制，并验证绑定后是否超过最大层级
     */
    private void validateDistributionLevel(DistributionUser inviter) {
        // 获取分销配置
        DistributionConfig config = distributionConfigService.selectDistributionConfigByConfigId(1L);
        if (config == null) {
            throw new ServiceException("分销配置信息不存在");
        }

        // 获取配置的最大层级
        int maxLevel = Integer.parseInt(config.getMaxLevel());

        // 如果最大层级为1，则不允许发展下级
        if (maxLevel <= 1) {
            throw new ServiceException("当前分销配置不允许发展下级");
        }

        // 检查邀请人的层级深度
        int inviterLevel = calculateDistributorLevel(inviter.getDistributorId());

        // 如果邀请人层级已经达到或超过最大层级限制，则不允许绑定下级
        if (inviterLevel >= maxLevel) {
            throw new ServiceException("邀请人已达到最大分销层级限制，无法继续发展下级");
        }

        // 关键修复：检查绑定后是否会超过最大层级
        // 邀请人层级 + 新下级（层级为1） = 总层级
        if (inviterLevel + 1 > maxLevel) {
            throw new ServiceException("绑定后将超过最大层级限制（当前最大：" + maxLevel + "层），无法绑定");
        }

        // 检查邀请人的上级层级（防止超过二级限制）
        if (maxLevel == 2 && inviter.getFatherId() != null && inviter.getFatherId() > 0) {
            DistributionUser father = distributionUserMapper.selectDistributionUserByDistributorId(inviter.getFatherId());
            if (father != null && father.getFatherId() != null && father.getFatherId() > 0) {
                throw new ServiceException("分销层级已超过二级限制，无法添加下级");
            }
        }
    }

    /**
     * 计算分销员的层级深度
     * @param distributorId 分销员ID
     * @return 层级深度（1表示一级分销员，2表示二级分销员，以此类推）
     */
    private int calculateDistributorLevel(Long distributorId) {
        int level = 1; // 默认层级为1

        DistributionUser current = distributionUserMapper.selectDistributionUserByDistributorId(distributorId);
        if (current == null) {
            return level;
        }

        // 向上追溯层级
        Long fatherId = current.getFatherId();
        while (fatherId != null && fatherId > 0) {
            DistributionUser father = distributionUserMapper.selectDistributionUserByDistributorId(fatherId);
            if (father == null) {
                break;
            }
            level++;
            fatherId = father.getFatherId();

            // 防止无限循环，设置最大层级限制为10
            if (level > 10) {
                break;
            }
        }

        return level;
    }

    /**
     * 检查用户申请状态
     */
    private DistributionUser checkUserApplicationStatus(Long userId) {
        DistributionUser existingUser = distributionUserMapper.selectDistributionUserByUserId(userId);
        if (existingUser != null && !"2".equals(existingUser.getAuthStatus())) {
            throw new ServiceException("该用户已开通分销员资格或正在审核中");
        }
        return existingUser;
    }

    /**
     * 验证上级关系 - 二级分销核心逻辑
     */
    private void validateSuperiorRelation(DistributionUser distributionUser, DistributionConfig config) {
        Long fatherId = distributionUser.getFatherId();

        // 如果没有设置上级，直接设置为平台直属
        if (fatherId == null || fatherId == 0L) {
            distributionUser.setFatherId(0L);
            return;
        }

        // 检查上级是否存在且有效
        DistributionUser fatherUser = distributionUserMapper.selectDistributionUserByDistributorId(fatherId);
        if (fatherUser == null || !"1".equals(fatherUser.getAuthStatus())) {
            throw new ServiceException("上级分销员不存在或未通过审核");
        }

        // 获取配置的最大层级
        int maxLevel = Integer.parseInt(config.getMaxLevel());

        // 检查上级的层级，确保不超过最大层级
        if (maxLevel <= 1) {
            throw new ServiceException("当前分销配置不允许发展下级");
        }

        // 如果上级还有上级，检查是否超过二级
        if (fatherUser.getFatherId() != 0L) {
            // 查询上级的上级
            DistributionUser grandfatherUser = distributionUserMapper.selectDistributionUserByDistributorId(fatherUser.getFatherId());
            if (grandfatherUser != null && grandfatherUser.getFatherId() != 0L) {
                throw new ServiceException("分销层级已超过配置限制，无法添加下级");
            }
        }
    }

    /**
     * 创建新的分销员申请
     */
    private int createNewApplication(DistributionUser distributionUser, DistributionConfig config) {
        // 设置分销员基本信息
        setupDistributionUserInfo(distributionUser);

        // 插入分销员记录
        int result = insertDistributionUser(distributionUser);
        if (result <= 0 || distributionUser.getDistributorId() == null) {
            throw new ServiceException("创建分销员记录失败");
        }

        // 更新上级团队关系
        // 注意：申请时不更新团队关系，只在审核通过时更新
        // updateSuperiorTeamRelation(distributionUser);

        // 建立分销关系记录
        // createDistributionRelations(distributionUser);

        // 初始化分销员钱包
        initializeDistributionWallet(distributionUser.getDistributorId());

        // 记录操作日志
        recordDistributionLog(distributionUser.getDistributorId(), "5", "分销员申请",
                "用户提交分销员申请", JSON.toJSONString(distributionUser), "");

        return result;
    }

    /**
     * 设置分销员基本信息
     */
    private void setupDistributionUserInfo(DistributionUser distributionUser) {
        // 获取默认等级
        DistributionGrade defaultGrade = distributionGradeService.selectDefaultGrade();
        if (defaultGrade == null || defaultGrade.getGradeId() == null) {
            throw new ServiceException("默认分销等级配置异常");
        }

        // 设置等级信息
        distributionUser.setGradeId(defaultGrade.getGradeId());

        // 设置状态信息
        distributionUser.setDistributorCode(IdUtils.generateDistributorCode());
        distributionUser.setAuthStatus("0"); // 审核中
        distributionUser.setTeamCount(1L); // 团队总人数初始化为1（包括自己）
        distributionUser.setDirectCount(0L); // 直接下级人数初始化为0
        distributionUser.setStatus("0"); // 正常
        distributionUser.setDelFlag("0"); // 未删除
        distributionUser.setCreateTime(new Date());
        distributionUser.setCreateBy(SecurityUtils.getUsername());
        distributionUser.setBindTime(new Date());
    }

    /**
     * 更新上级团队关系
     */
    private void updateSuperiorTeamRelation(DistributionUser distributionUser) {
        updateSuperiorTeamRelationWithTeamCount(distributionUser, 1L);
    }

    /**
     * 更新上级团队关系（带团队规模参数）
     */
    private void updateSuperiorTeamRelationWithTeamCount(DistributionUser distributionUser, long teamCount) {
        if (distributionUser.getFatherId() != null && distributionUser.getFatherId() != 0L) {
            // 更新直接上级的直接下级人数和团队人数
            DistributionUser father = distributionUserMapper.selectDistributionUserByDistributorId(distributionUser.getFatherId());
            if (father != null) {
                father.setDirectCount(father.getDirectCount() == null ? 1L : father.getDirectCount() + 1);
                father.setTeamCount(father.getTeamCount() == null ? teamCount : father.getTeamCount() + teamCount);
                distributionUserMapper.updateDistributionUser(father);

                // 如果有祖父级（一级分销员），更新祖父级的团队总人数
                if (father.getFatherId() != null && father.getFatherId() != 0L) {
                    DistributionUser grandfather = distributionUserMapper.selectDistributionUserByDistributorId(father.getFatherId());
                    if (grandfather != null) {
                        grandfather.setTeamCount(grandfather.getTeamCount() == null ? teamCount : grandfather.getTeamCount() + teamCount);
                        distributionUserMapper.updateDistributionUser(grandfather);
                    }
                }
            }
        }
    }

    /**
     * 建立分销关系记录
     */
    private void createDistributionRelations(DistributionUser distributionUser) {
        if (distributionUser.getFatherId() != null && distributionUser.getFatherId() != 0L) {
            // 1. 建立与直接上级的一级关系
            createRelationRecord(distributionUser.getFatherId(), distributionUser.getDistributorId(), "1");

            // 2. 如果直接上级还有上级，建立与祖父级的二级关系
            DistributionUser father = distributionUserMapper.selectDistributionUserByDistributorId(distributionUser.getFatherId());
            if (father != null && father.getFatherId() != null && father.getFatherId() != 0L) {
                createRelationRecord(father.getFatherId(), distributionUser.getDistributorId(), "2");
            }
        }
    }

    /**
     * 创建单个关系记录
     */
    private void createRelationRecord(Long distributorId, Long subordinateId, String relationLevel) {
        DistributionRelation relation = new DistributionRelation();
        relation.setDistributorId(distributorId);
        relation.setSubordinateId(subordinateId);
        relation.setRelationLevel(relationLevel);
        relation.setBindTime(new Date());
        relation.setIsActive("1");
        relation.setStatus("0");
        relation.setDelFlag("0");
        relation.setCreateTime(new Date());
        relation.setCreateBy(SecurityUtils.getUsername());
        distributionRelationMapper.insertDistributionRelation(relation);
    }

    /**
     * 更新被拒绝的申请
     */
    private int updateRejectedApplication(DistributionUser existingUser, DistributionUser newUser) {
        // 只更新基本信息，保持原有的上级关系
        updateUserBasicInfo(existingUser, newUser);
        existingUser.setAuthStatus("0"); // 重新设置为待审核
        existingUser.setUpdateTime(new Date());
        existingUser.setUpdateBy(SecurityUtils.getUsername());

        int result = distributionUserMapper.updateDistributionUser(existingUser);
        if (result > 0) {
            recordDistributionLog(existingUser.getDistributorId(), "5", "分销员重新申请",
                    "用户重新提交分销员申请", JSON.toJSONString(existingUser), "");
        }
        return result;
    }

    /**
     * 更新用户基本信息
     */
    private void updateUserBasicInfo(DistributionUser existingUser, DistributionUser newUser) {
        existingUser.setRealName(newUser.getRealName());
        existingUser.setMobile(newUser.getMobile());
        existingUser.setIdentityCard(newUser.getIdentityCard());
    }

    /**
     * 初始化分销员钱包
     */
    private void initializeDistributionWallet(Long distributorId) {
        try {
            DistributionWallet wallet = new DistributionWallet();
            wallet.setDistributorId(distributorId);
            wallet.setAvailableBalance(BigDecimal.ZERO);
            wallet.setFrozenBalance(BigDecimal.ZERO);
            wallet.setTotalIncome(BigDecimal.ZERO);
            wallet.setTotalWithdraw(BigDecimal.ZERO);
            wallet.setWalletStatus("0"); // 正常
            wallet.setStatus("0"); // 上架
            wallet.setDelFlag("0"); // 未删除
            walletService.insertDistributionWallet(wallet);
        } catch (Exception e) {
            log.error("初始化分销员钱包失败", e);
            throw new ServiceException("初始化分销员钱包失败: " + e.getMessage());
        }
    }

    /* ===========================================================  */

    /**
     * 记录分销操作日志
     *
     * @param distributorId 分销员ID
     * @param logType 日志类型
     * @param action 操作动作
     * @param changeObject 变更对象
     * @param changeDetail 变更详情
     * @param remark 备注
     */
    public void recordDistributionLog(Long distributorId, String logType, String action,
                                     String changeObject, String changeDetail, String remark) {
        try {
            // 创建日志对象
            DistributionLog log = new DistributionLog();
            log.setDistributorId(distributorId);
            // 设置日志类型
            log.setLogType(logType);
            // 设置操作动作
            log.setAction(action);
            // 设置变更对象
            log.setChangeObject(changeObject);
            // 设置变更详情
            log.setChangeDetail(changeDetail);
            // 设置备注
            log.setRemark(remark);
            // 设置日志编码
            log.setLogCode(IdUtils.generateLogCode());

            // 获取请求信息
            HttpServletRequest request = ServletUtils.getRequest();
            if (request != null) {
                log.setIpAddress(request.getRemoteAddr());
                log.setUserAgent(request.getHeader("User-Agent"));
            }

            log.setStatus("0");
            log.setDelFlag("0");
            distributionLogService.insertDistributionLog(log);
        } catch (Exception e) {
            // 日志记录失败不影响主流程
            log.error("记录分销操作日志失败", e);
        }
    }


    /**
     * 查询分销用户信息列表
     * 
     * @param distributionUser 分销用户信息
     * @return 分销用户信息
     */
    @Override
    public List<DistributionUser> selectDistributionUserList(DistributionUser distributionUser)
    {
        return distributionUserMapper.selectDistributionUserList(distributionUser);
    }

    /**
     * 新增分销用户信息
     * 
     * @param distributionUser 分销用户信息
     * @return 结果
     */
    @Override
    public int insertDistributionUser(DistributionUser distributionUser)
    {
        distributionUser.setCreateTime(DateUtils.getNowDate());
        distributionUser.setCreateBy(SecurityUtils.getUsername());
        return distributionUserMapper.insertDistributionUser(distributionUser);
    }

    /**
     * 修改分销用户信息
     * 
     * @param distributionUser 分销用户信息
     * @return 结果
     */
    @Override
    public int updateDistributionUser(DistributionUser distributionUser)
    {
        distributionUser.setUpdateTime(DateUtils.getNowDate());
        return distributionUserMapper.updateDistributionUser(distributionUser);
    }

    /**
     * 批量删除分销用户信息
     * 
     * @param distributorIds 需要删除的分销用户信息主键
     * @return 结果
     */
    @Override
    public int deleteDistributionUserByDistributorIds(Long[] distributorIds)
    {
        return distributionUserMapper.deleteDistributionUserByDistributorIds(distributorIds);
    }

    /**
     * 删除分销用户信息信息
     * 
     * @param distributorId 分销用户信息主键
     * @return 结果
     */
    @Override
    public int deleteDistributionUserByDistributorId(Long distributorId)
    {
        return distributionUserMapper.deleteDistributionUserByDistributorId(distributorId);
    }

    /**
     * 获取分销员详情
     *
     * @param userId 用户ID
     * @return 分销员详情
     */
    @Override
    public DistributorDetailVo getDistributorDetail(Long userId) {
        // 1. 获取分销员基本信息
        DistributionUser distributionUser = selectDistributionUserByUserId(userId);
        if (distributionUser == null) {
            throw new ServiceException("当前用户不是分销员");
        }
        // 获取分销员ID
        Long distributorId = distributionUser.getDistributorId();

        // 2. 获取分销钱包信息
        DistributionWallet walletInfo = walletService.selectWalletByDistributorId(distributorId);
        if (walletInfo == null) {
            throw new ServiceException("当前用户没有分销钱包");
        }

        // 3. 获取用户基本信息(头像、昵称)
        SysUser userInfo = userService.selectUserById(userId);
        if (userInfo == null) {
            throw new ServiceException("当前用户信息异常");
        }

        String avatarUrl = userInfo.getAvatar();
        String nickName = userInfo.getNickName();

        // 4. 获取上级分销员信息
        String superiorName = "无";
        if (distributionUser.getFatherId() != null && distributionUser.getFatherId() > 0) {
            // 获取上级分销员信息
            DistributionUser superior = distributionUserMapper.selectDistributionUserByDistributorId(distributionUser.getFatherId());
            superiorName = superior != null ? superior.getRealName() : "无";
        }

        // 5. 获取分销等级信息(假设已有等级服务)
        String levelName = "普通分销员";
        BigDecimal nextLevelThreshold = BigDecimal.ZERO;
        if (distributionUser.getGradeId() != null) {
            DistributionGrade grade = distributionGradeService.selectDistributionGradeByGradeId(distributionUser.getGradeId());
            levelName = grade != null ? grade.getGradeName() : levelName;

            // 获取下一级门槛
            DistributionGrade nextGrade = distributionGradeService.selectNextGrade(distributionUser.getGradeId());
            if (nextGrade != null) {
                nextLevelThreshold = nextGrade.getMinOrderAmount() != null ? nextGrade.getMinOrderAmount() : BigDecimal.ZERO;
            }
        }

        // 6. 计算今日/本月佣金(需实现佣金服务)
        BigDecimal todayCommission = walletService.calculateTodayCommission(distributionUser.getDistributorId());
        BigDecimal monthlyCommission = walletService.calculateMonthlyCommission(distributionUser.getDistributorId());

        // 7. 构建返回对象
        DistributorDetailVo detailVo = new DistributorDetailVo();

        // 构建分销员信息
        DistributorInfoVo distributorInfo = new DistributorInfoVo();
        // 填充数据
        distributorInfo.setDistributorId(distributionUser.getDistributorId()); // 分销员ID
        distributorInfo.setDistributorCode(distributionUser.getDistributorCode()); // 分销员编号
        distributorInfo.setRealName(distributionUser.getRealName()); // 真实姓名
        distributorInfo.setPhone(distributionUser.getMobile()); // 手机号
        distributorInfo.setIdCard(distributionUser.getIdentityCard()); //  身份证号

        distributorInfo.setAvatar(userInfo.getAvatar()); // 头像
        distributorInfo.setNickname(userInfo.getNickName()); // 昵称
        // 填充等级信息
        distributorInfo.setLevel(levelName); // 等级名称
        distributorInfo.setTotalEarnings(walletInfo.getTotalIncome()); // 总收入
        distributorInfo.setNextLevelThreshold(nextLevelThreshold); // 下级门槛

        distributorInfo.setSuperiorId(distributionUser.getFatherId());
        distributorInfo.setSuperior(superiorName); // 上级名称
        // 获取上级信息
        DistributionUser father = distributionUserMapper.selectDistributionUserByDistributorId(distributionUser.getFatherId());
        distributorInfo.setSuperiorCode(father != null ? father.getDistributorCode() : null); // 上级编号
//        DistributionUser father = distributionUserMapper.selectDistributionUserByDistributorId(distributionUser.getFatherId());
//        distributorInfo.setSuperiorCode(father.getDistributorCode()); // 上级编号

        // 构建佣金信息
        CommissionInfoVo commissionInfo = new CommissionInfoVo();
        // 填充数据
        commissionInfo.setWithdrawAble(walletInfo.getAvailableBalance());
        commissionInfo.setToday(todayCommission);
        commissionInfo.setMonthly(monthlyCommission);
        commissionInfo.setTotal(walletInfo.getTotalIncome());

        detailVo.setDistributor(distributorInfo);
        detailVo.setCommission(commissionInfo);
        detailVo.setFanCount(distributionUser.getDirectCount() != null ? distributionUser.getDirectCount().intValue() : 0);

        return detailVo;
    }

    /**
     * 获取分销员ID
     *
     * @param userId 用户ID
     * @return 分销员ID
     */
    @Override
    public Long selectDistributorWhereUserId(Long userId) {
        return distributionUserMapper.selectDistributorWhereUserId(userId);
    }

    /**
     * 获取待审核分销员数量
     */
    @Override
    public int selectPendingDistributorCount() {
        return distributionUserMapper.selectPendingDistributorCount();
    }

    /**
     * 获取分销员摘要列表
     *
     * @param distributor 分销员信息
     * @return 分销员摘要列表
     */
    @Override
    public List<DistributionUser> selectDistributorSummaryList(DistributionUser distributor) {
        return distributionUserMapper.selectDistributorSummaryList(distributor);
    }

    /**
     * 新增分销钱包信息
     *
     * @param distributionUser 分销用户信息对象
     */
    public void insertDistributionWallet(DistributionUser distributionUser)
    {
        List<DistributionWallet> distributionWalletList = distributionUser.getDistributionWalletList();
        Long distributorId = distributionUser.getDistributorId();
        if (StringUtils.isNotNull(distributionWalletList))
        {
            List<DistributionWallet> list = new ArrayList<DistributionWallet>();
            for (DistributionWallet distributionWallet : distributionWalletList)
            {
                distributionWallet.setDistributorId(distributorId);
                list.add(distributionWallet);
            }
            if (list.size() > 0)
            {
                distributionUserMapper.batchDistributionWallet(list);
            }
        }
    }

    /**
     * 获取所有分销员基础信息列表（仅包含ID和姓名）
     *
     * @return 分销员基础信息列表
     */
    @Override
    public List<DistributionUser.DistributorBasicInfo> selectDistributorBasicList() {
        return distributionUserMapper.selectDistributorBasicList();
    }

    /**
     * 手动绑定上级分销员
     *
     * @param distributorId 当前分销员ID
     * @param superiorDistributorCode 上级分销员编码
     * @param remark 绑定备注
     * @return 绑定结果
     */
    @Override
    @Transactional
    public int bindSuperiorDistributor(Long distributorId, String superiorDistributorCode, String remark) {
        // 1. 验证分销功能是否开启
        DistributionConfig config = validateDistributionFunction();

        // 2. 获取当前分销员信息
        DistributionUser currentDistributor = distributionUserMapper.selectDistributionUserByDistributorId(distributorId);
        if (currentDistributor == null) {
            throw new ServiceException("当前分销员信息不存在");
        }

        // 3. 检查当前分销员状态
        if (!"0".equals(currentDistributor.getStatus()) || !"1".equals(currentDistributor.getAuthStatus())) {
            throw new ServiceException("当前分销员状态异常，无法绑定上级");
        }

        // 4. 检查是否已经有上级
        if (currentDistributor.getFatherId() != null && currentDistributor.getFatherId() > 0) {
            throw new ServiceException("该分销员已绑定上级，无法重复绑定");
        }

        // 5. 获取上级分销员信息
        DistributionUser superiorDistributor = distributionUserMapper.selectDistributorByDistributorCode(superiorDistributorCode);
        if (superiorDistributor == null) {
            throw new ServiceException("上级分销员信息不存在");
        }

        // 6. 校验上级分销员状态
        if (!"0".equals(superiorDistributor.getStatus()) || !"1".equals(superiorDistributor.getAuthStatus())) {
            throw new ServiceException("上级分销员状态异常，无法绑定");
        }

        // 7. 检查是否试图绑定自己
        if (superiorDistributor.getDistributorId().equals(distributorId)) {
            throw new ServiceException("不能绑定自己为上级");
        }

        // 8. 检查分销层级规则
        validateDistributionLevel(superiorDistributor);

        // 9. 设置上级关系
        currentDistributor.setFatherId(superiorDistributor.getDistributorId());
        currentDistributor.setUpdateTime(new Date());
        currentDistributor.setUpdateBy(SecurityUtils.getUsername());

        int result = distributionUserMapper.updateDistributionUser(currentDistributor);

        // 10. 如果当前分销员已审核通过，立即更新团队关系
        if ("1".equals(currentDistributor.getAuthStatus())) {
            updateSuperiorTeamRelation(currentDistributor);
            createDistributionRelations(currentDistributor);
        }

        // 11. 记录绑定日志
        recordDistributionLog(
                distributorId,
                "8",
                "手动绑定上级",
                "分销员绑定上级关系",
                "绑定上级分销员：" + superiorDistributorCode + "，上级ID：" + superiorDistributor.getDistributorId() + "，备注：" + remark,
                superiorDistributorCode);

        // 12. 记录上级分销员的日志
        recordDistributionLog(
                superiorDistributor.getDistributorId(),
                "1",
                "新增下级",
                "下级分销员绑定",
                "新增下级分销员：" + currentDistributor.getDistributorCode() + "，下级ID：" + distributorId,
                currentDistributor.getDistributorCode());

        return result;
    }


    /**
     * 禁用分销员并处理相关返佣
     * @param distributorId 分销员ID
     * @param remark 禁用原因
     */
    public void disableDistributorAndHandleCommission(Long distributorId, String remark) {
        try {
            // 1. 获取分销员信息
            DistributionUser distributor = selectDistributionUserByDistributorId(distributorId);
            if (distributor == null) {
                throw new ServiceException("分销员不存在");
            }

            // 2. 更新分销员状态为禁用
            distributor.setStatus("1"); // 1-禁用
            distributor.setUpdateTime(new Date());
            updateDistributionUser(distributor);
            log.info("分销员 {} 已禁用", distributorId);

            // 3. 查找该分销员相关的待结算分销订单记录
            List<DistributionOrderRelation> pendingRelations = distributionOrderRelationMapper.selectPendingRelationsByDistributorId(distributorId);

            // 4. 取消这些订单的返佣资格
            for (DistributionOrderRelation relation : pendingRelations) {
                // 更新分销状态为"已取消"
                relation.setDistributionStatus("3"); // 3-已取消
                relation.setCancelReason("分销员被禁用: " + remark);
                relation.setUpdateTime(new Date());
                distributionOrderRelationMapper.updateDistributionOrderRelation(relation);

                log.info("因分销员禁用，取消订单 {} 的返佣资格", relation.getOrderId());
            }

            // 5. 记录操作日志
            recordDistributionLog(distributorId, "6", "禁用分销员", "系统操作", remark, "");

        } catch (Exception e) {
            log.error("禁用分销员并处理返佣时发生异常，分销员ID: {}", distributorId, e);
            throw new ServiceException("禁用分销员失败: " + e.getMessage());
        }
    }

    /**
     * 生成分销商品海报
     *
     * @param distributorId 分销员ID
     * @param productId 商品ID
     * @return 海报信息
     */
    @Override
    @Transactional
    public Map<String, Object> generateProductPoster(Long distributorId, Long productId) {
        // 1. 验证分销员权限
        DistributionUser distributor = distributionUserMapper.selectDistributionUserByDistributorId(distributorId);
        if (distributor == null) {
            throw new ServiceException("分销员不存在");
        }

        // 2. 生成唯一的场景ID (Scene ID)
        String sceneId = IdUtils.fastUUID(); // 或使用其他方式生成唯一ID

        // 3. 创建海报记录 (这里简化处理，实际应该创建专门的海报记录表)
        // 记录包含: sceneId, distributorId, productId, 生成时间, 过期时间等

        // 4. 生成二维码 (模拟实现，实际应调用微信API或其他二维码生成库)
        String qrCodeUrl = generateProductQRCode(sceneId, distributorId, productId);

        // 5. 构建返回信息
        Map<String, Object> posterInfo = new HashMap<>();
        posterInfo.put("sceneId", sceneId);
        posterInfo.put("qrCodeUrl", qrCodeUrl);
        posterInfo.put("distributorId", distributorId);
        posterInfo.put("productId", productId);
        posterInfo.put("expiresIn", 2592000); // 30天有效期(秒)

        // 可以添加更多海报信息，如商品信息、分销员信息等
        return posterInfo;
    }

    /**
     * 生成商品二维码
     *
     * @param sceneId 场景ID
     * @param distributorId 分销员ID
     * @param productId 商品ID
     * @return 二维码URL
     */
    private String generateProductQRCode(String sceneId, Long distributorId, Long productId) {
        // 实际实现应该:
        // 1. 调用微信API生成小程序二维码
        // 2. 或使用ZXing等库生成二维码图片
        // 3. 保存二维码图片到服务器或云存储
        // 4. 返回二维码图片URL

        // 示例返回格式
        return "/api/qrcode/product?scene=" + sceneId;
    }


}
